<template>
  <div class="areaDialog" v-show="openArea">
    <div class="close">
      <el-icon>
        <Close @click="closeSelect" />
      </el-icon>
    </div>
    <!-- 行政区域选择 -->
    <el-form :model="form" :rules="rules" ref="rulesForm" label-width="100px">
      <el-form-item label="选择地区" prop="taskDistrict" style="width:280px">
        <el-cascader v-model="form.taskDistrict" placeholder="请选择地区" :props="cascaderProps"
                     separator="," collapse-tags collapse-tags-tooltip @change="getCheckedArea"
                     ref="checkedAreaRef" :options="optionsSelect">
        </el-cascader>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="xzqhAdd" type="primary">确定</el-button>
      <el-button @click="clearXzqh" type="primary">清空</el-button>
    </div>
  </div>
</template>

<script setup>
import {getAreaTree,getDistrictBoundary} from "@/api/taskmanage/sceneExame"
import { getProvinces, getYear, getDistrict } from "@/utils/group.js";

const { proxy } = getCurrentInstance();
const props = defineProps(['open','selectDistrict']);
const emits = defineEmits(['close','getSelectXzqhGeom','getSelectDistrict'])
const loading = ref(false);
const openArea = ref(false);
const cascaderProps = {
  multiple: true
};
const taskDistrictName = ref("");
const districtListName = ref("");
const checkedAreaRef = ref();
const districtTreeList = ref([]);
const districtBoundaryList = ref([]); //行政区划经纬度信息
const districtCount = ref(0); //选择的行政区划数量

const data = reactive({
  form: {
    taskDistrict: "",
  },
  selectProvince: [],
  listData: [],
  queryParams: {
    page: 1,
    rows: 10,
    taskNum: "",
    taskName: "",
    taskStatus: "",
    province: "",
    city: "",
    county: "",
  },
  queryParamsAdd: {
    taskYear: "",
    taskNum: "",
    taskName: "",
    taskArea: "",
    taskRegion: "",
    parentdistrictList: [],
    taskDistrict: '',
    groupName: "",
    groupLeader: "",
    groupId: "",
    groupLeaderId: "",
    regionCodes: "" //地图行政区划code,code字符串
  },
  optionsSelect: [],
  selectArea: []
});

let {
  form,
  queryParams,
  listData,
  queryParamsAdd,
  optionsSelect,
  selectArea,
} = toRefs(data);

const rules = reactive({
  taskDistrict: [{
    required: true,
    message: "请选择地区",
    trigger: "change"
  }],
});

/*地图传参start*/
const completeRefreshData = ref(false);//防止刷新后地图不显示
const xzqhSelect = () => { //行政区划选择区域
  areaSelect();
}
/*地图传参end*/

// 打开行政选区
function areaSelect() {
  openArea.value = true;
  resetArea();
}
// 选择关闭后的回调
function closeSelect() {
  openArea.value = false;
  emits('close', true)
  resetArea();
}

function resetArea() {
  selectArea.value = [];
  proxy.resetForm("rulesForm");
}

function getCheckedArea() {
  let taskDistrict = checkedAreaRef.value.getCheckedNodes();
  taskDistrict = taskDistrict.filter(option => !(option.parent && option.parent.checked))
  console.log(taskDistrict, "选中值");
  queryParamsAdd.value.parentdistrictList = taskDistrict.map((item, index) => {
    return item.pathLabels.join("-");
  });
  var arr = JSON.parse(JSON.stringify(queryParamsAdd.value.parentdistrictList));
  queryParamsAdd.value.parentdistrictList = arr;
  taskDistrictName.value = getDistrict(arr);
  districtListName.value = getProvinces(taskDistrictName.value);
}

// 部门  树形数据
// 处理数据
function disposeata(data) {
  data.forEach((item) => {
    item.label = item.name;
    item.key = item.id;
    item.children && disposeata(item.children);
  });
  return data;
}

function getTreeselect() {
  console.log("查询行政区划列表：");
  getAreaTree().then((response) => {
    nextTick(() => {
      //console.log(response.data);
      optionsSelect.value = disposeata(JSON.parse(response.data));
      console.log("行政区划列表");
      //地图行政区划列表
      districtTreeList.value = optionsSelect.value;
      console.log(districtTreeList.value);
    });
  });
}

//根据所有省市县全名字符串获取codelist
function getCodeByAllName(allName) {
  let allCodeList = [];
  if(allName != null && allName != "") {
    let array = allName.split("、");
    //获取行政区划树列表
    let treeList = districtTreeList.value;
    for(let i = 0; i < array.length; i++) {
      let name = array[i];
      let code = null;
      let arr = name.split('-');
      if(arr.length == 1) { //省或直辖市
        if(treeList != null && treeList.length > 0) {
          for(let i = 0; i < treeList.length; i++) {
            let provinceData = treeList[i]; //省节点
            if(provinceData != null) {
              let provinceName = provinceData.name; //省
              if(name == provinceName) {
                let provinceCode = provinceData.code; //省编码
                code = provinceCode;
                break;
              }
            }
          }
        }
      } else if(arr.length == 2) { //市或直辖市的区县
        if(treeList != null && treeList.length > 0) {
          for(let i = 0; i < treeList.length; i++) {
            let provinceData = treeList[i]; //省节点
            if(provinceData != null) {
              let provinceName = provinceData.name; //省
              if(arr[0] == provinceName) {
                let bool = false;
                let cityList = provinceData.children; //市列表
                if(cityList != null) {
                  for(let j = 0; j < cityList.length; j++) {
                    let cityData = cityList[j];
                    if(cityData != null) {
                      let cityName = cityData.name; //市
                      if(arr[1] == cityName) {
                        let cityCode = cityData.code; //市编码
                        code = cityCode;
                        bool = true;
                        break;
                      }
                    }
                  }
                }
                if(bool) {
                  break;
                }
              }
            }
          }
        }
      } else if(arr.length == 3) { //区县
        if(treeList != null && treeList.length > 0) {
          for(let i = 0; i < treeList.length; i++) {
            let provinceData = treeList[i]; //省节点
            let bool = false;
            if(provinceData != null) {
              let provinceName = provinceData.name; //省
              if(arr[0] == provinceName) {
                let cityList = provinceData.children; //市列表
                if(cityList != null) {
                  for(let j = 0; j < cityList.length; j++) {
                    let cityData = cityList[j];
                    if(cityData != null) {
                      let cityName = cityData.name; //市
                      if(arr[1] == cityName) {
                        let areaList = cityData.children; //区县列表
                        if(areaList != null) {
                          for(let j = 0; j < areaList.length; j++) {
                            let areaData = areaList[j];
                            if(areaData != null) {
                              let areaName = areaData.name; //区县
                              if(arr[2] == areaName) {
                                let areaCode = areaData.code; //区县编码
                                code = areaCode;
                                bool = true;
                                break;
                              }
                            }
                          }
                        }
                        if(bool) {
                          break;
                        }
                      }
                    }
                  }
                }
              }
            }
            if(bool) {
              break;
            }
          }
        }
      }
      //添加code
      allCodeList.push(code);
    }
  }

  return allCodeList;
}

// 确定选择行政区划
function xzqhAdd() {
  proxy.$refs.rulesForm.validate(valid => {
    if (valid) {
      closeSelect();
      proxy.$modal.loading("正在查询，请稍候...");
      districtBoundaryList.value = []; //行政区划经纬度信息
      //查询行政区划经纬度信息
      console.log("查询行政区划经纬度信息");
      console.log(taskDistrictName.value);
      //地图获取行政区划总面积
      //let area = getAllSelectArea(queryParamsAdd.value.parentdistrictList);
      //queryParamsAdd.value.taskArea = area.toString();
      //根据所有省市县全名字符串获取codelist
      let codeList = getCodeByAllName(taskDistrictName.value);
      console.log("查询行政区划codeList");
      console.log(codeList);
      //选择的行政区划数量
      districtCount.value = codeList.length;
      console.log("选择的行政区划数量" + districtCount.value);
      let regionCodes = "";
      for(let i = 0; i < codeList.length; i++) {
        let code = codeList[i];
        if(i > 0) {
          regionCodes += ",";
        }
        regionCodes += code;
      }
      queryParamsAdd.value.regionCodes = regionCodes; //地图行政区划code,code字符串
      //查询行政区划经纬度信息
      getDistrictBoundaryByCode(codeList);
    }else{
      proxy.$modal.msgWarning("请选取行政区划");
    }
  });
}

//清空行政区划
function clearXzqh(){
  form.value.taskDistrict = "";
  //清空获取行政区划选择区域空间数据
  emits('getSelectXzqhGeom', null);
}

//查询行政区划经纬度信息
function getDistrictBoundaryByCode(codeList) {
  let geomList = [];//空间数据列表
  for(let m = 0; m < codeList.length; m++) {
    let code = codeList[m];
    //查询行政区划经纬度信息
    console.log("查询行政区划经纬度信息" + code);
    getDistrictBoundary(code).then((response) => {
      nextTick(() => {
        console.log("查询行政区划经纬度信息result:");
        console.log(response.data);
        geomList.push(response.data.coordinate);
        //districtBoundaryList.value.push(response.data.coordinate);
        //截取数据防止报错--仅用于展示不保存
        let subStr = response.data.coordinate;
        subStr = subStr.substring(0, 1000);
        districtBoundaryList.value.push(subStr);
        if(districtCount.value == districtBoundaryList.value.length) { //判断是否全部查询完毕
          let region = "";
          let list = districtBoundaryList.value;
          for(let i = 0; i < list.length; i++) {
            if(i > 0) {
              region += ";";
            }
            region += list[i];
          }
          console.log("全部查询完毕--行政区划经纬度信息");
          queryParamsAdd.value.taskRegion = region;
          //地图获取行政区划总面积
          let area = getAllSelectArea(queryParamsAdd.value.parentdistrictList);
          queryParamsAdd.value.taskArea = area.toString();
          proxy.$modal.closeLoading();
          console.log(geomList);
          //获取行政区划选择区域空间数据
          emits('getSelectXzqhGeom', geomList);
          //获取行政区划选择区域
          emits('getSelectDistrict', form.value.taskDistrict);
        }
      });
    });
  }
}

//获取行政区划总面积
function getAllSelectArea(array){
  let areaCount = 0;
  console.log(array.length);
  if(array!=null && array.length>0){
    for(let i=0;i<array.length;i++){
      let name = array[i];
      let arr = name.split('-');
      console.log(name+","+arr.length);
      if(arr.length==1){//省
        let province = arr[0];
        let areaTemp = getAreaByAllName("1",province,null,null);//根据行政区划全称获取省市区面积信息
        console.log("areaTemp"+areaTemp);
        areaCount += areaTemp;
        console.log("areaCount"+areaCount);
      }else if(arr.length==2){//市或直辖市的区县
        let province = arr[0];
        let city = arr[1];
        let areaTemp = getAreaByAllName("2",province,city,null);//根据行政区划全称获取省市区面积信息
        console.log("areaTemp"+areaTemp);
        areaCount += areaTemp;
        console.log("areaCount"+areaCount);
      }else if(arr.length==3){//区县
        let province = arr[0];
        let city = arr[1];
        let area = arr[2];
        let areaTemp = getAreaByAllName("3",province,city,area);//根据行政区划全称获取省市区面积信息
        console.log("areaTemp"+areaTemp);
        areaCount += areaTemp;
        console.log("areaCount"+areaCount);
      }
    }
  }
  if(areaCount>0){
    areaCount = areaCount.toFixed(3);//四舍五入保留3位小数
  }

  return areaCount;
}
function getAreaByAllName(type,province,city,area){//根据行政区划全称获取省市区面积信息
  //type:0省 | 1市 | 2区县
  let areaCount = 0;
  let districtTreeDataList = districtTreeList.value;
  if(districtTreeDataList!=null && districtTreeDataList!=""){
    //获取行政区划树列表
    let treeList = districtTreeDataList;
    if(treeList!=null && treeList.length>0){
      for(let i=0;i<treeList.length;i++){
        let provinceData = treeList[i];//省节点
        if(provinceData!=null){
          let provinceName = provinceData.name;//省
          if(type=="1" && province==provinceName){
            let cityList = provinceData.children;//市列表
            if(cityList!=null){
              for(let j=0;j<cityList.length;j++){
                let cityData = cityList[j];
                if(cityData!=null){
                  let areaList = cityData.children;//区县列表
                  if(areaList!=null && areaList.length>0){
                    for(let j=0;j<areaList.length;j++){
                      let areaData = areaList[j];
                      if(areaData!=null){
                        areaCount += areaData.area / 1000000;//平方公里
                      }
                    }
                  }else{//直辖市
                    areaCount += cityData.area / 1000000;//平方公里
                  }
                }
              }
            }
            return areaCount;
          }
          let cityList = provinceData.children;//市列表
          if(cityList!=null){
            for(let j=0;j<cityList.length;j++){
              let cityData = cityList[j];
              if(cityData!=null){
                let cityName = cityData.name;//市
                if(type=="2" && city==cityName){
                  let areaList = cityData.children;//区县列表
                  if(areaList.length>0){
                    for(let j=0;j<areaList.length;j++){
                      let areaData = areaList[j];
                      if(areaData!=null){
                        areaCount += areaData.area / 1000000;//平方公里
                      }
                    }
                  }else{//直辖市的区县
                    areaCount = cityData.area / 1000000;//平方公里
                  }
                  return areaCount;
                }
                let areaList = cityData.children;//区县列表
                if(areaList!=null){
                  for(let j=0;j<areaList.length;j++){
                    let areaData = areaList[j];
                    if(areaData!=null){
                      let areaName = areaData.name;//区县
                      if(type=="3" && area==areaName){
                        areaCount += areaData.area / 1000000;//平方公里
                        return areaCount;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  return areaCount;
}

//是否显示
const isOpen = watch(() => props.open, value => {// watch函数监听props.open
  openArea.value = value;
},{immediate:true});

//获取行政区划选择区域
const isSelectDistrict = watch(() => props.selectDistrict, value => {// watch函数监听props.selectDistrict
  form.value.taskDistrict = value;
},{immediate:true});

onMounted(() => {
  getTreeselect();
})
</script>

<style scoped lang="scss">
.mapDiv {
  position:absolute;top:0px;left:0px;width:100%;height:100%;
}
.areaDialog {
  text-align: center;
  .close {
    text-align: right;
    .el-icon {
      color: #606266;
      padding: 20px 0;
      margin-right: 10px;
      right: 0px;
      font-size: 22px;
    }
  }
  width: 320px;
  position: absolute;
  top: 270px;
  left: 320px;
  background: rgba($color: #fff, $alpha: 0.9);
  padding-bottom: 28px;
}
</style>